package com.zyb.patient.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

public class HttpUtils {

	/****** GET ******/
	public static String httpGetQuery(String url, Map map) {
		BufferedReader in = null;
		try {
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					Constant.REQUEST_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, Constant.SO_TIMEOUT);

			HttpClient httpclient = new DefaultHttpClient(httpParams);
			httpclient.getParams().setParameter("utf8", "utf-8");
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			if (map == null) {
				map = new HashMap();
			}
			Iterator iter = map.keySet().iterator();
			while (iter.hasNext()) {
				String name = (String) iter.next();
				String value = (String) map.get(name);
				 params.add(new BasicNameValuePair(name, value));
			}
			URI uri = URIUtils.createURI(null, url, -1, null,
					URLEncodedUtils.format(params, HTTP.UTF_8), null);
			LogUtil.e("uri:" + uri);
			HttpGet httpget = new HttpGet(uri);
			HttpResponse response = httpclient.execute(httpget);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}

			in.close();
			String page = sb.toString();
			LogUtil.e("info:" + page);
			if (page.startsWith("\ufeff")) {
				return page.substring(1);
			} else {
				return page;
			}
		} catch (Exception e) {
			LogUtil.e("e:" + e.toString());
			e.printStackTrace();
		}
		return null;
	}

	/****** POSt ******/
//	http://api.zyb.job.zhumingkai.cn/?s=main/get_initialize&device_code=1235&token=123
	@SuppressWarnings("rawtypes")
	public static String httpPostQuest(String url, Map map) {
		BufferedReader in = null;
		/* 建立HTTP Post连线 */
		HttpPost httpRequest = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		try {
			if (map.isEmpty()) {
				map = new HashMap();
			}
			Iterator iter = map.keySet().iterator();

			while (iter.hasNext()) {
				String name = (String) iter.next();
				String value = (String) map.get(name);
				params.add(new BasicNameValuePair(name,value));
			}
			// 发出HTTP request
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			// 取得HTTP response
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			LogUtil.e("StatusCode:"
					+ httpResponse.getStatusLine().getStatusCode());
			// 若状态码为200 ok
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				in = new BufferedReader(new InputStreamReader(httpResponse
						.getEntity().getContent()));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				while ((line = in.readLine()) != null) {
					sb.append(line);
				}
				in.close();
				String page = sb.toString();
				LogUtil.e("info:" + page);
				return page;
			} else {
				LogUtil.e("info:null");
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/****** 上传文件(图片和音频等) ******/
	public static String upLoadFormFile(String url, Map<String, String> paths,
			Map<String, String> contents) {
		String info = "";
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		MultipartEntity reqEntity = new MultipartEntity();
		httpPost.setEntity(reqEntity);

		/** file param name */
		Iterator<String> iterator = paths.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			// Log.e("FileBodyvalue:", paths.get(key)+"");
			try {
				FileBody value = new FileBody(new File(paths.get(key)));
				reqEntity.addPart(key, value);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		/** String param name */
		Iterator<String> it = contents.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			LogUtil.e("StringBodykey:" + key);
			try {
				LogUtil.e("StringBodyvalue:" + contents.get(key) + "");
				StringBody value = new StringBody(URLEncoder.encode(
						contents.get(key), "UTF-8"),
						Charset.forName(HTTP.UTF_8));
				reqEntity.addPart(key, value);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		try {
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				info = inputStream2String(responseEntity.getContent());
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		httpClient.getConnectionManager().shutdown();
		return info;

	}

	public static String inputStream2String(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}

//	public static String httpGetQuery2(String url, String path, Map map) {
//		BufferedReader in = null;
//		try {
//			BasicHttpParams httpParams = new BasicHttpParams();
//			HttpConnectionParams.setConnectionTimeout(httpParams,
//					Constant.REQUEST_TIMEOUT);
//			HttpConnectionParams.setSoTimeout(httpParams, Constant.SO_TIMEOUT);
//
//			HttpClient httpclient = new DefaultHttpClient(httpParams);
//			httpclient.getParams().setParameter("utf8", "utf-8");
//			List<NameValuePair> params = new ArrayList<NameValuePair>();
//			// List qparams = new ArrayList();
//			JSONObject params2 = new JSONObject();
//			if (map == null) {
//				map = new HashMap();
//			}
//			Iterator iter = map.keySet().iterator();
//			while (iter.hasNext()) {
//				String name = (String) iter.next();
//				if (name.equals("communityPic") || name.equals("housePic")) {
//					params2.put(name, new JSONArray((String) map.get(name)));
//				} else {
//					String value = (String) map.get(name);
//					params2.put(name, value);
//				}
//				// String name = (String) iter.next();
//				// qparams.add(new BasicNameValuePair(name, (String)
//				// map.get(name)));
//			}
//			String data = params2.toString().replaceAll("\\\\", "")
//					.replaceAll("\\\\\"", "\"");
//			LogUtil.e("data -->" + data);
//			params.add(new BasicNameValuePair("data", data));
//			// if(path!=null){
//			URI uri = URIUtils.createURI(null, url, -1, "/" + path,
//					URLEncodedUtils.format(params, HTTP.UTF_8), null);
//			// }else{
//			// URI uri = URIUtils.createURI("http" , url , -1 , null ,
//			// URLEncodedUtils.format(qparams , HTTP.UTF_8) , null);
//			// }
//			LogUtil.e("uri:" + uri);
//			HttpGet httpget = new HttpGet(uri);
//			// httpget.setParams(httpParams);
//			HttpResponse response = httpclient.execute(httpget);
//			in = new BufferedReader(new InputStreamReader(response.getEntity()
//					.getContent()));
//			StringBuffer sb = new StringBuffer("");
//			String line = "";
//			while ((line = in.readLine()) != null) {
//				sb.append(line);
//			}
//
//			in.close();
//			String page = sb.toString();
//			// System.out.println("info:" + page);
//			if (page.startsWith("\ufeff")) {
//				return page.substring(1);
//			} else {
//				return page;
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}
}
